package tesis.sin.rest.parser;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javassist.CannotCompileException;
import javassist.NotFoundException;
import tesis.sin.model.Mensaje;
import tesis.sin.model.Noticia;
import tesis.sin.rest.clasesusuario.GeneradorClase;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

public class JsonParser {
	
	private static JsonParser parser;
	private ObjectMapper mapper;
		
	private JsonParser(){}
		
	public static JsonParser getJsonParser()
	{
		if(JsonParser.parser == null)
		{
			JsonParser.parser = new JsonParser();
			JsonParser.parser.setMapper(new ObjectMapper());
		}
		return JsonParser.parser;
	}
	
	public ObjectMapper getMapper() {
		return mapper;
	}

	public void setMapper(ObjectMapper mapper) {
		this.mapper = mapper;
	}

	public static Mensaje jsonAMensaje(String json) throws JsonProcessingException, IOException
	{
		return JsonParser.getJsonParser().getMapper().readValue(json, Mensaje.class);
	}
	
	public static Noticia jsonANoticia(String json) throws JsonProcessingException, IOException
	{
		return JsonParser.getJsonParser().getMapper().readValue(json, Noticia.class);
	}
	
	public static String objetoAJson(Object objeto, String... atributos) throws JsonProcessingException, IOException
	{
		SimpleModule module = new SimpleModule("custom",Version.unknownVersion());
		module.addSerializer(Object.class, new SerializadorObjetos(atributos));
		JsonParser.getJsonParser().getMapper().registerModule(module);
		return JsonParser.getJsonParser().getMapper().writeValueAsString(objeto);
	}

	public Class jsonClase(String nombreClase, String json) throws JsonProcessingException, IOException, NotFoundException, CannotCompileException{
		JsonNode raiz = JsonParser.getJsonParser().getMapper().readTree(json);
		Map<String, Class<?>> propiedades = new HashMap<String, Class<?>>();
		Iterator<String> fields = raiz.fieldNames();
		while(fields.hasNext())
		{
			String fieldName = fields.next();
			JsonNode field = raiz.get(fieldName);
			if(field.isInt())
				propiedades.put(fieldName, Integer.class);
			else if(field.isTextual())
				propiedades.put(fieldName, String.class);
		}
		Class clase = GeneradorClase.generarClase(nombreClase, propiedades);
		return clase;
	}
}
